package com.shanks.framework.mq.configuration;

import com.shanks.framework.mq.processor.AckMQProcessor;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import net.javacrumbs.shedlock.support.CustomizedTemplateLockProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.sql.DataSource;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@ComponentScan("com.shanks.framework.mq")
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")
public class BaseMQConfiguration {

    /**
     * 执行任务使用的异步队列
     *
     * @return
     */
    @Bean(name = "mqTaskAsyncTakExcutor")
    public AsyncTaskExecutor mqTaskAsyncTakExcutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(10);
        threadPoolTaskExecutor.setMaxPoolSize(40);
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        threadPoolTaskExecutor.setQueueCapacity(2400);
        return threadPoolTaskExecutor;
    }

    /**
     * 定时任务任务使用的对列
     *
     * @return
     */
    @Bean(name = "mqTaskScheduleTakExcutor")
    public ScheduledExecutorService mqTaskScheduleTakExcutor() {
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutors = new ScheduledThreadPoolExecutor(10);
        scheduledThreadPoolExecutors.setMaximumPoolSize(32);
        scheduledThreadPoolExecutors.setKeepAliveTime(60, TimeUnit.SECONDS);
        return scheduledThreadPoolExecutors;
    }

    @Bean
    public LockProvider lockProvider(DataSource dataSource) {
        return new CustomizedTemplateLockProvider(
                JdbcTemplateLockProvider.Configuration.builder()
                        .withJdbcTemplate(new JdbcTemplate(dataSource))
                        .withTableName("message_shedlock")
                        .build());
    }

    @Bean
    public AckMQProcessor ackMQProcessor() {
        return new AckMQProcessor();
    }
}
